package com.general.app.xtgl.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.general.app.xtgl.dao.entity.AssessUserModel;
import com.general.app.xtgl.dao.entity.CompanyModel;
import com.general.app.xtgl.dao.entity.RelationModel;
import com.general.app.xtgl.service.IAssessUserService;
import com.general.app.xtgl.service.ICompanyService;
import com.general.common.action.FileImportAction;
import com.general.common.model.QueryModel;
import com.general.common.security.entity.User;
import com.general.utils.base.Constant;
import com.general.utils.base.StringUtil;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack; 

/**
 * 用户信息管理
 * @author qilm
 *
 */
public class AssessUserAction extends FileImportAction implements ModelDriven<AssessUserModel>{

	private static final long serialVersionUID = -5571279048868407604L;
	
	private AssessUserModel model = new AssessUserModel();
	private IAssessUserService assessUserService;
	private ICompanyService companyService;

	/**
	 * 导入文件
	 */
	private File excelFile;
	
	/**
	 * 保存原始文件名     
	 */
    private String excelFileName; 
    
	/**
	 * 用户信息管理列表
	 * @return
	 */
	public String assessUserList(){
		if (QUERY.equals(model.getDoType())) {
			QueryModel queryModel = model.getQueryModel();
			try {
				queryModel.setItems(assessUserService.getPagedList(model));
			} catch (Exception e) {
				e.printStackTrace();
			}
			getValueStack().set(DATA, queryModel);
			return DATA;
		}
		return "assessUserList";
	}	
	
	/**
	 * 用户增加面页
	 * @return
	 */
	public String assessUserAdd(){		

		ValueStack vs = getValueStack();
		List<CompanyModel> companyList = companyService.getPagedList(new CompanyModel());
		vs.set("companyList", companyList);
		return "assessUserAdd";
	}
	
	/**
	 * 保存用户信息
	 * @return
	 */
	public String saveAssessUserAdd(){
		try {
			User user = getCurrentUser();
			model.setInsert_nm(user.getUserid());
			model.setUpdate_nm(user.getUserid());
			String userId = UUID.randomUUID().toString();
			model.setUser_id(userId);
			boolean result = assessUserService.insert(model);
			String key = result ? Constant.SAVE_SUCCEE : Constant.SAVE_FAIL;
			// 跳转到用户关系面页时，回传userid
			if("relation".equals(getRequest().getParameter("type"))){
				getValueStack().set("userId", userId);
				return "relation";
			}
			getValueStack().set(DATA, getText(key));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return DATA;
	}

	
	/**
	 * 用户修改面页
	 * @return
	 */
	public String assessUserMod(){
		
		ValueStack vs = getValueStack();
		String ids = getRequest().getParameter("ids");
		AssessUserModel assessUserModel = assessUserService.getModel(ids);
		try {
			List<CompanyModel> companyList = companyService.getPagedList(new CompanyModel());
			vs.set("companyList", companyList);
			vs.set("model", assessUserModel);
			BeanUtils.copyProperties(model, assessUserModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "assessUserMod";
	}
	
	
	
	/**
	 * 保存用户修改面页
	 * @return
	 */
	public String saveAssessUserMod(){
		try {
			User user = getCurrentUser();
			model.setUpdate_nm(user.getUserid());
			boolean result = assessUserService.update(model);
			String key = result ? Constant.SAVE_SUCCEE : Constant.SAVE_FAIL;
			getValueStack().set(DATA, getText(key));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return DATA;
	}
	/**
	 * 用户关系维护面页
	 * @return
	 */
	public String assessUserSet(){

		ValueStack vs = getValueStack();
		String ids = getRequest().getParameter("ids");
		AssessUserModel assessUserModel = assessUserService.getModel(ids);
		try {
			// 初始化用户关系列表
			List<RelationModel> relationList = assessUserService
					.getRelationList(assessUserModel.getUser_id(),
							assessUserModel.getCompany_id());

			vs.set("model", assessUserModel);
			vs.set("relationList", relationList);
			//设定用户的
			BeanUtils.copyProperties(model, assessUserModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "assessUserSet";
	}
	
	
	/**
	 * 保存用户关系维护面页
	 * @return
	 */
	public String saveAssessUserSet(){
		try {
			boolean result = assessUserService.updateRelation(model);
			String key = result ? Constant.SAVE_SUCCEE : Constant.SAVE_FAIL;
			getValueStack().set(DATA, getText(key));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return DATA;
	}
	/**
	 * 删除用户信息
	 * @return
	 */
	public String assessUserDel(){

		String ids = getRequest().getParameter("ids");
		try {
			String message = assessUserService.scAssessUser(ids);
			getValueStack().set(DATA, message);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return DATA;
	}
	
	/**
	 * 导入用户信息面页跳转
	 * @return
	 */
	public String assessUserImport(){
		return "assessUserImport";		
	}

	/**
	 * 导入用户信息
	 * @return
	 * @throws Exception 
	 */
	public String importAssessUser() throws Exception{
		try {
			boolean bolFlg = false;
			List<List<Object>> excelList = null;
			String fileContentType = getRequest().getParameter("fileContentType");
			Workbook book = null;
			if(fileContentType.equalsIgnoreCase("xls")){    
				book =  new HSSFWorkbook(new FileInputStream(excelFile));   
				
				// 读取数据
				excelList = read2003Excel((HSSFSheet)book.getSheetAt(0));
	        }else if(fileContentType.equalsIgnoreCase("xlsx")){
	        	
	        	 book =  new XSSFWorkbook(new FileInputStream(excelFile));  

				// 读取数据
				excelList = read2007Excel((XSSFSheet)book.getSheetAt(0));
	        } 
			
			if( excelList!=null && excelList.size()!=0){
				bolFlg = readExcelList(excelList);
			}

			String key = bolFlg ? Constant.SAVE_SUCCEE : Constant.SAVE_FAIL;
			getValueStack().set(DATA, getText(key));
		} catch (IOException e) {
			e.printStackTrace();
			getValueStack().set(DATA, getText(Constant.SAVE_FAIL));
			return DATA;
		}
		return DATA;
	}

	/**
	 * 解析 excelList
	 * @param excelList
	 */
	private boolean readExcelList(List<List<Object>> excelList){
		try{
			User user = getCurrentUser();
			// 是否有被评估者
			String assessFlg = "0";
			List<AssessUserModel> insertUserLst = new ArrayList<AssessUserModel>();
			Set assessSet =new HashSet();
			assessSet.clear();
			List<AssessUserModel> relationModelLst = new ArrayList<AssessUserModel>();
			if(excelList!=null && excelList.size()!=0){
				// 单位ID
				String companyId = "";

				AssessUserModel relationModel = new AssessUserModel();
				
				Set superiorSet=new HashSet();
				Set equalSet=new HashSet();
				Set subordinateSet=new HashSet();
				for(int i =0; i<excelList.size();i++){
					
					//取行
					List<Object> row = excelList.get(i);
					
					// 第一行判断是不是[公司名称],有则取得companyId
					if( i==0 ){
						String companyInit = row.get(0).toString();
						// 不匹配验证
						if(!Constant.EXCEL_COMPANY_NAME.equalsIgnoreCase(companyInit)){
							return false;
						}
						// 单位名称
						String companyName = row.get(1).toString().trim();
						if(!"".equalsIgnoreCase(companyName)){

							CompanyModel company = companyService.getModelByName(companyName);
							if(company !=null ) companyId = company.getCompany_id();
							if(companyId == null || "".equalsIgnoreCase(companyId)){
								CompanyModel model = new CompanyModel();
								String id = UUID.randomUUID().toString();
								model.setCompany_id(id);
								model.setCompany_name(companyName);
								model.setInsert_nm(user.getUserid());
								model.setUpdate_nm(user.getUserid());
								boolean result = companyService.insert(model);
								if(result){
									companyId = id;
								}else{
									return false;
								}
							}
						}
					}else{
						//列数不满 返回
						if(row.size() < 4 ){
							break;
						}
						
						// 取得[类型，姓名，邮箱地址，手机，部门，职位]
						String relation = row.get(0).toString().trim();
						String userNm = row.get(1).toString().trim();
						String email = row.get(2).toString().trim();
						String phone = row.get(3).toString().trim();
						String department = "";
						String position = "";
						if(row.size() > 4) department = String.valueOf(row.get(4)).trim();
						if(row.size() > 5) position = String.valueOf(row.get(5)).trim();
						
						// 第二行判断是不是[类型，姓名，邮箱地址，手机，部门，职位]
						if( i==1 &&!( Constant.EXCEL_RELATION.equalsIgnoreCase(relation)
								&& Constant.EXCEL_USER_NAME.equalsIgnoreCase(userNm)
								&& Constant.EXCEL_EMAIL.equalsIgnoreCase(email)
								&& Constant.EXCEL_PHONE.equalsIgnoreCase(phone)
								&& Constant.EXCEL_DEPARTMENT.equalsIgnoreCase(department)
								&& Constant.EXCEL_POTION.equalsIgnoreCase(position))){
							return false;
							
							// 第二行之后的判断
						}else if(i > 1 ){

							// 如果关系/姓名/手机/邮箱有未填的则返回
							if(StringUtils.EMPTY.equals(relation)
									|| StringUtils.EMPTY.equals(userNm)
									|| StringUtils.EMPTY.equals(email)
									|| StringUtils.EMPTY.equals(phone)){
								return false;
							}
							// 取出当前行的USER_ID
							String userLine = "";
							AssessUserModel n = new AssessUserModel();
							
							//通过姓名、邮箱、手机、单位来读取是否是已存在用户
							n.setUser_nm(userNm);
							n.setUser_email(email);
							n.setUser_phone(phone);
							n.setCompany_id(companyId);
							//n.setDepartment(department);
							//n.setPosition(position);							
							
							// 该用户已在数据库存在
							AssessUserModel us = assessUserService.getModel(n);
							if(us!=null && us.getUser_id() != ""){
								// 更新个人信息
								n.setCompany_id(companyId);
								n.setUpdate_nm(user.getUsername());
								n.setUser_id(us.getUser_id());
								assessUserService.update(n);
								
								// 取得个人ID
								userLine = us.getUser_id();
								
								// 该用户不存在在数据库
							}else{
								
								// 判断是否存在在插入列表里有该用户
								for(AssessUserModel inUser : insertUserLst){
									
									// 如果存在
									if(userNm.equalsIgnoreCase(inUser.getUser_nm())
											&& email.equalsIgnoreCase(inUser.getUser_email())
											&& phone.equalsIgnoreCase(inUser.getUser_phone())){
										userLine = inUser.getUser_id();
										break;
									}
								}
								// 没存在历史信息 也没存在数据库则插入
								if("".equalsIgnoreCase(userLine)){
									
									userLine = UUID.randomUUID().toString();
									
									// 设定用户
									n.setUser_id(userLine);
									n.setCompany_id(companyId);
									n.setInsert_nm(user.getUserid());
									n.setUpdate_nm(user.getUserid());
									// 插入到需要插入的列表
									insertUserLst.add(n);	
								}
							}
							
							// 类型是否正确、被评估者/相关人员 判断是否有填写email/phone
							if(!(Constant.EXCEL_RELATION_ASSESS.equalsIgnoreCase(relation)
									|| Constant.EXCEL_RELATION_SUPERIOR.equalsIgnoreCase(relation)
									|| Constant.EXCEL_RELATION_EQUAL.equalsIgnoreCase(relation)
									|| Constant.EXCEL_RELATION_SUBORDINATE.equalsIgnoreCase(relation))
									|| "".equalsIgnoreCase(userNm) 
									|| "".equalsIgnoreCase(email)
									|| "".equalsIgnoreCase(phone)){
								
								//若不正确则返回
								return false;
							}
							
							// 如果是被评估者
							if(Constant.EXCEL_RELATION_ASSESS.equalsIgnoreCase(relation)){
								assessFlg = "1";
								
								assessSet.add(userLine);
								
								// 判断不是第一个被评估者
								if(relationModel.getUser_id()!=null){
									
									// 上平下任意一级有人
									if (!superiorSet.isEmpty()
										|| !equalSet.isEmpty()
										|| !subordinateSet.isEmpty()) {

										relationModel.setSuperior(StringUtil.getHashSetString(superiorSet));
										relationModel.setEqual(StringUtil.getHashSetString(equalSet));
										relationModel.setSubordinate(StringUtil.getHashSetString(subordinateSet));
										
										relationModelLst.add(relationModel);
									}
								}
								
								// 重置关系用户
								superiorSet = new HashSet();
								equalSet = new HashSet();
								subordinateSet = new HashSet();
								
								relationModel = new AssessUserModel();
								
								// 取得已存在的user_id,插入到关系表里
								relationModel.setUser_id(userLine);
							}
							
							// 如果有被评估者则继续，否则不读取数据
							if("1".equalsIgnoreCase(assessFlg)){
								if(Constant.EXCEL_RELATION_SUPERIOR.equalsIgnoreCase(relation)){
									superiorSet.add(userLine);
								}else if(Constant.EXCEL_RELATION_EQUAL.equalsIgnoreCase(relation)){
									equalSet.add(userLine);
								}else if(Constant.EXCEL_RELATION_SUBORDINATE.equalsIgnoreCase(relation)){
									subordinateSet.add(userLine);
								}
							}
						}
					}
				}
				
				// 判断不是第一个被评估者
				if(relationModel.getUser_id()!=null){
					
					// 上平下任意一级有人
					if (!superiorSet.isEmpty()
						|| !equalSet.isEmpty()
						|| !subordinateSet.isEmpty()) {

						relationModel.setSuperior(StringUtil.getHashSetString(superiorSet));
						relationModel.setEqual(StringUtil.getHashSetString(equalSet));
						relationModel.setSubordinate(StringUtil.getHashSetString(subordinateSet));
						
						relationModelLst.add(relationModel);
					}
				}
			}else{
				return false;
			}
			
			// 插入数据库user表
			if(insertUserLst !=null && insertUserLst.size()>0){
				int countUser = assessUserService.batchInsert(insertUserLst);
			}
			
			// 插入关系表
			if(relationModelLst !=null && relationModelLst.size()>0){
				int countRelation = assessUserService.batchInsertRelation(relationModelLst);
			}
			
			// 更新用户表的assessFlg
			if(!"".equals(StringUtil.getHashSetString(assessSet))){
				assessUserService.batchUpdateAssessFlg(StringUtil.getHashSetString(assessSet));				
			}
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	public String getExcelFileName() {
		return excelFileName;
	}

	public void setExcelFileName(String excelFileName) {
		this.excelFileName = excelFileName;
	}

	public File getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(File excelFile) {
		this.excelFile = excelFile;
	}
	
	public AssessUserModel getModel() {
		return model;
	}

	public void setModel(AssessUserModel model) {
		this.model = model;
	}

	public IAssessUserService getAssessUserService() {
		return assessUserService;
	}

	public void setAssessUserService(IAssessUserService assessUserService) {
		this.assessUserService = assessUserService;
	}

	public ICompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(ICompanyService companyService) {
		this.companyService = companyService;
	}

}
